package com.yunzong.iot.utils.encrypt;

import android.util.Base64;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 * 3des 加密、解密
 * @author 克林
 */
public class SecureUtils {

    private static final String AlgorithmWithMode = "DESede/ECB/PKCS5Padding";
    private static final String Algorithm = "DESede";

    /**
     * 转换成十六进制字符串
     *
     * @param key
     * @return
     */
    private static byte[] hex(String key) {

        byte[] bkeys = key.getBytes();
        byte[] enk = new byte[24];
        System.arraycopy(bkeys, 0, enk, 0, 24);
        return enk;
    }


    /**
     * 3DES加密
     * 模式 ECB/NoPadding
     *
     * @param key    密钥，24位
     * @param srcStr 将加密的字符串
     * @return
     */
    public static String encode3Des(String key, String srcStr) {
        byte[] keybyte = hex(key);
        byte[] src = srcStr.getBytes();
        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
            //加密
            Cipher c1 = Cipher.getInstance(AlgorithmWithMode);
            c1.init(Cipher.ENCRYPT_MODE, deskey);

            String pwd = Base64.encodeToString(c1.doFinal(src), Base64.NO_WRAP);
//           return c1.doFinal(src);//在单一方面的加密或解密
            return pwd;
        } catch (java.security.NoSuchAlgorithmException e1) {
            // TODO: handle exception
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }

    /**
     * 3DES解密
     * 模式 ECB/NoPadding
     *
     * @param key    加密密钥，长度为24字节
     * @param desStr 解密后的字符串
     * @return
     */
    public static String decode3Des(String key, String desStr) {

        byte[] keybyte = hex(key);
        byte[] src = Base64.decode(desStr,Base64.NO_WRAP);

        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
            //解密
            Cipher c1 = Cipher.getInstance(AlgorithmWithMode);
            c1.init(Cipher.DECRYPT_MODE, deskey);
            byte[] bytesPwd = c1.doFinal(src);
            String pwd = new String(bytesPwd);
            return pwd;
        } catch (java.security.NoSuchAlgorithmException e1) {
            // TODO: handle exception
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }

}
